package cn.xm.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.List;

@Component
@Slf4j
public class LoginFilter implements Order, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("path:{}",path);
        // 访问的不是公共资源并且没有token就拦截并返回错误信息
        if (!path.endsWith("login") && !path.endsWith("register")) {
            // 获取token
            List<String> token = request.getHeaders().get("token");
            // 若果token为空
            if (token == null || token.size()==0) {
                // 获取响应对象
                ServerHttpResponse response = exchange.getResponse();
                // 设置返回结果
                HashMap<String, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","该用户未登录。");
                map.put("code",401);
                // map装换为json字符串再转换为数组
                String jsonString = JSON.toJSONString(map);
                byte[] bytes = jsonString.getBytes();
                // 包装到buffer
                DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
                // 设置状态为401,断掉后面的filter
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                // 设置响应编码字符集
                response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
                // 把结果写到响应返回给客户端
                return response.writeWith(Mono.just(dataBuffer));
            }
        }
        // 访问的是公共资源或者有token都放行
        return chain.filter(exchange);

    }

    @Override
    public int value() {
        return 0;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }
}
